<template>
    <div>
        <div class="top-img">
            <img style="width: 100%" src="https://img.js.design/assets/img/617766b867e5da8dd2a409b5.png" alt="">
        </div>
        <div class="bottom-content">
            <el-card>
<!--                {{registerForm}}-->
                <el-form
                        :label-position="'top'"
                        ref="registerFormRef"
                        :model="registerForm"
                        status-icon
                        :rules="registerRules"
                        label-width="120px"
                        class="demo-ruleForm"
                >
                    <el-row justify="center" v-show="!orgLock">
                        <el-col :span="10">
                            <div class="searchOrg">
                                <h2>请选择您的报名机构</h2>
                                <el-form-item prop="org_code">
                                    <span>报名机构代码：</span><el-input v-model="registerForm.org_code" autocomplete="off"/>
                                </el-form-item>
                            </div>
                            <div class="searchOrg-button">
                                <el-button type="primary" :disabled="registerForm.org_code ? false:true"
                                           @click="getOrg">提交
                                </el-button>
                            </div>
                        </el-col>
                        <el-col :span="20">
                            <div class="explain">
                                <h4>说明</h4>
                                <p>如果需要，这里可以放一些关于产品的常见问题说明，如果需要，这里可以放一些关于产品的常见问题说明，如果需要，这里可以放一些关于产品的常见问题说明，如果需要，这里可以放一些关于产品的常见问题说明，</p>
                            </div>
                        </el-col>
                    </el-row>
                    <div v-show="orgLock" class="orgLockDiv">
                        <div v-show="!is_sign_up">
                            <el-row :gutter="2" justify="space-around">
                                <el-col :span="8">
                                    <el-form-item label="请选择您要报读的机构" prop="">
                                        <el-input :disabled="true" v-model="registerForm.org_name" autocomplete="off"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="请您选择报读薪酬管理职业技能等级课程级别" prop="course_id">
                                        <el-select
                                                style="width: 100%"
                                                v-model="registerForm.course_id"
                                                placeholder="请您选择报读薪酬管理职业技能等级课程级别"
                                        >
                                            <el-option
                                                    v-for="item in courseList"
                                                    :key="item.id"
                                                    :label="item.name"
                                                    :value="item.id"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="2" justify="space-around">
                                <el-col :span="8">
                                    <el-form-item label="学员姓名" prop="name">
                                        <el-input placeholder="请输入学员姓名" v-model="registerForm.name" autocomplete="off"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="所在地区" prop="province">
                                        <el-cascader
                                                style="width: 100%"
                                                :options="areaOptions"
                                                v-model="selectedOptions"
                                                @change="addressChange"
                                                placeholder="请选择所在地区"
                                        >
                                        </el-cascader>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="2" justify="space-around">
                                <el-col :span="8">
                                    <el-form-item label="证件类型" prop="card_type">
                                        <el-select
                                                style="width: 100%"
                                                v-model="registerForm.card_type"
                                                placeholder="请选择证件类型"
                                        >
                                            <el-option
                                                    v-for="item in cardOptions"
                                                    :key="item.id"
                                                    :label="item.name"
                                                    :value="item.id"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="证件号码" prop="card_id">
                                        <el-input placeholder="请输入您的证件号码" v-model="registerForm.card_id" autocomplete="off"/>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="2" justify="space-around">
                                <el-col :span="8">
                                    <el-form-item label="电子邮箱" prop="email">
                                        <el-input placeholder="请输入您的电子邮箱" v-model="registerForm.email" autocomplete="off"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">

                                </el-col>
                            </el-row>
                            <el-row :gutter="2" justify="space-around">
                                <el-col :span="8">
                                    <el-form-item label="手机号码" prop="phone">
                                        <el-input placeholder="请输入您的手机号码" v-model="registerForm.phone" autocomplete="off"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="验证码" prop="msg_code">
                                        <el-input placeholder="请输入验证码" v-model="registerForm.msg_code" autocomplete="off">
                                            <template #suffix>
                                                <tencent-captcha :phone="registerForm.phone" :phoneRule="validatePhone" scene="2"
                                                                 class="rule-password">
                                                </tencent-captcha>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="2" justify="space-around">
                                <el-col :span="8">
                                    <el-form-item>
                                        <el-checkbox v-model="isAffirm" label="本人承诺在申请薪酬管理职业技能时所提供的个人信息及材料真实、合法、有效，否则将承担一切责任及后果" size="large" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">

                                </el-col>
                            </el-row>
                            <el-row justify="center" style="padding-top: 50px">
                                <el-col :span="2">
                                    <el-form-item>
                                        <el-button type="primary" @click="submitForm(registerFormRef)"
                                        >提交
                                        </el-button
                                        >
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                        <div v-show="is_sign_up">
                            <el-row justify="center">
                                <el-col :sm="12" :lg="6">
                                    <div style="margin: 0 auto">
                                        <el-result
                                                icon="success"
                                                title="报名成功"
                                                sub-title=""
                                        >
                                            <template #extra>
                                                <div style="display: flex">
                                                    <el-button type="primary" @click="toPersonCenter">进入学员中心</el-button>
                                                    <el-button @click="close">退出登录</el-button>
                                                </div>
                                            </template>
                                        </el-result>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script>
    import Cookies from 'js-cookie'
    import {useStore} from 'vuex';
    import TencentCaptcha from "../TencentCaptcha/TencentCaptcha";
    import {reactive, ref, toRefs,toRaw} from 'vue'
    import {org_detail, profile, sign_up} from "../../request/api";
    import {ElMessage} from "element-plus";
    import {areaData, textToCode, codeToText} from "@/utils/JdAreaData/areaData";
    import {useRouter} from "vue-router";

    export default {
        name: "index",
        props:['registerId'],
        setup(props,{emit}) {
            let store = useStore();
            let router = useRouter();
            const registerFormRef = ref(null)

            let data = reactive({
                areaOptions: areaData, //省市区三级联动
                selectedOptions: [], //选择后的省市区对象数组
                is_sign_up:false,
                isAffirm:false,
                orgLock: false,
                cardOptions: [
                    {id: 1, name: "居民身份证"},
                    {id: 2, name: "护照"},
                    {id: 3, name: "港澳台胞身份证"},
                ],
                courseList: [],
                registerForm: {
                    org_code: '',
                    org_name: '',
                    course_id: '',
                    name: '',
                    province: '',
                    city: '',
                    region: '',
                    card_type: 1,
                    card_id: '',
                    phone: '',
                    msg_code: '',
                    email:''
                }
            })
            console.log('registerId',props.registerId)
            let getCurrentRegister = (currentId) =>{
                profile({pid:currentId}).then(res =>{
                    data.registerForm = res;
                    data.registerForm.msg_code = '';
                    data.registerForm.course_id = '';
                    data.selectedOptions = textToCode([data.registerForm.province, data.registerForm.city, data.registerForm.region])
                    console.log('赋值后的对象',data.registerForm);
                })
            }
            if(props.registerId){
                getCurrentRegister(toRaw(props.registerId));
            }

            const addressChange = (arr) =>{
                [data.registerForm.province, data.registerForm.city, data.registerForm.region] = codeToText(arr);
            }

            const validateOrgCode = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('机构代码不能为空'))
                } else {
                    callback()
                }
            };
            const validateCourseId = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('报读课程不能为空'))
                } else {
                    callback()
                }
            };
            const validateCardId = (rule, value, callback) => {
                if (data.registerForm.card_type == 1) {
                    let reg =
                        /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
                    if (value === "") {
                        callback(new Error("请填写身份证号码"));
                    } else if (!reg.test(value)) {
                        callback(new Error("身份证格式错误"));
                    } else {
                        callback();
                    }
                } else if (data.registerForm.card_type == 2) {
                    let reg = /^[A-Z,a-z,\d]+$/;
                    if (value === "") {
                        callback(new Error("请填写护照"));
                    } else if (!reg.test(value)) {
                        callback(new Error("护照格式错误"));
                    } else {
                        callback();
                    }
                } else if (data.registerForm.card_type == 3) {
                    let reg = /^[A-Z,a-z,\d]+$/;
                    if (value === "") {
                        callback(new Error("请填写港澳台胞证"));
                    } else if (!reg.test(value)) {
                        callback(new Error("证件格式错误"));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            };
            const validateName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('姓名不能为空'))
                } else {
                    callback()
                }
            };
            const validateCardType = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请选择证件类型'))
                } else {
                    callback()
                }
            };
            const validatePhone = (rule, value, callback) => {
                let phoneRule = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
                if (value === '') {
                    callback(new Error('手机号码不能为空'))
                } else if (!phoneRule.test(value)) {
                    callback(new Error("手机号码格式错误"))
                } else {
                    callback()
                }
            };
            const validateCode = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('验证码不能为空'))
                }else if(value.length != 4){
                    callback(new Error('验证码长度为4位'))
                } else {
                    callback()
                }
            };
            const province_rule = (rule, value, callback) => {
                if (data.registerForm.province === "" || data.registerForm.province == null) {
                    callback(new Error("请选择地区"));
                } else {
                    callback();
                }
            };
            const email_rule = (rule, value, callback) => {
                let reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                if (value === '') {
                    callback(new Error('电子邮箱不能为空'))
                } else if (!reg.test(value)) {
                    callback(new Error("电子邮箱格式错误"));
                } else {
                    callback()
                }
            };
            const registerRules = reactive({
                org_code: [{validator: validateOrgCode, trigger: 'blur'}],
                course_id: [{validator: validateCourseId, trigger: 'change'}],
                card_id: [{validator: validateCardId, trigger: 'blur'}],
                name: [{validator: validateName, trigger: 'blur'}],
                card_type: [{validator: validateCardType, trigger: 'blur'}],
                phone: [{validator: validatePhone, trigger: 'blur'}],
                msg_code: [{validator: validateCode, trigger: 'blur'}],
                province:[{validator: province_rule, trigger: 'blur'}],
                email:[{validator: email_rule, trigger: 'blur'}],
            })

            let getOrg = () => {
                org_detail({org_code: data.registerForm.org_code}).then(res => {
                    console.log(res)
                    data.registerForm.org_name = res.org_name
                    data.courseList = res.course;
                    data.orgLock = true
                }).catch(err => {
                    ElMessage({
                        type: 'error',
                        message: err.msg
                    })
                })
            }
            const submitForm = (formEl) => {
                if (!formEl) return
                formEl.validate((valid) => {
                    if (valid) {
                        if(data.isAffirm){
                            sign_up(data.registerForm).then(res =>{
                                console.log(res)
                                data.is_sign_up = true;
                            }).catch(err =>{
                                ElMessage({
                                    type:'error',
                                    message:err.msg + err.errors ? err.errors:''
                                })
                            })
                        }else{
                            ElMessage({
                                type:'warning',
                                message:'请确认并同意协议内容'
                            })
                        }
                    } else {
                        console.log('error submit!')
                        return false
                    }
                })
            }

            const resetForm = (formEl) => {
                if (!formEl) return
                formEl.resetFields()
            }

            const toPersonCenter = () =>{
                console.log(router.currentRoute.value.name)
                if(router.currentRoute.value.name != 'User'){
                    router.push({path:'/user'})
                }else{
                    emit('toPersonCenter','personCenter')
                }
            }

            const close = () =>{
                Cookies.remove('token');
                store.commit('setToken','')
                location.reload();
            }
            return {
                close,
                toPersonCenter,
                addressChange,
                validatePhone,
                getOrg,
                ...toRefs(data),
                registerFormRef,
                registerRules,
                submitForm,
                resetForm
            }
        },
        components: {
            TencentCaptcha
        }
    }
</script>

<style scoped>
    .explain{
        margin-top: 100px;
        background-color: rgba(248, 249, 251, 1);
        padding: 40px;
        border-radius: 10px;
    }
    .top-img {
        height: 260px;
        position: relative;
        overflow: hidden;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
    }

    .top-img img {
        position: absolute;
        left: 0;
        top: -75%;
    }

    .bottom-content {
        margin-top: 50px;
    }

    .searchOrg {

     }
    .searchOrg > h2 {
        text-align: center;
        padding: 60px 0px;
    }

    .searchOrg-button {
        text-align: center;
    }

    .orgLockDiv {
        padding: 40px;
    }
</style>
